<?php
namespace app\common\model;

use think\Model;
use think\Db;
use \app\common\libs\WeixinHelper;

class Config extends Model
{
    protected $table = 'config';
    var $key_name = 'wx_token'; 			// 微信token
    var $key_welcome = 'sub_welcome'; 			// 微信token
    var $key_selfmenu = 'self_menu'; 			// 微信微信公众号自定义菜单配置

    /*
	 * 获取微信token
     */
    function getToken() {
    	$token = '';
    	$time  = date('Y-m-d H:i:s');

		$config = $this->field('c_value')->where('c_name', $this->key_name)->where('expire_time', '>', $time)->find();

		if(is_null($config) || empty($config['c_value'])) {
			$request_token = WeixinHelper::getAccessToken();

			$data['c_name'] = $this->key_name;
			$data['c_value'] = $request_token['access_token'];
			$data['c_type'] = 'weixin';
			$data['description'] = '微信token';
			$data['expire_time'] = date('Y-m-d H:i:s', ($request_token['expires_in']-180));
			$data['create_time'] = $data['update_time'] = $time;

			Db::table($this->table)->insert($data, true);

			$token = $data['c_value'];
		} else {
			$token = $config['c_value'];
		}

		return $token;
    }

    function getWelcomeText() {
    	$data = $this->field('c_value')->where('c_name', $this->key_welcome)->find();
    	return is_null($data) ? config('weixin.subwelcome') : $data['c_value'];
    }

    /*
	 * 获取微信公众号自定义菜单配置
     */
    function getSelfMenu() {
    	$data = $this->field('c_value')->where('c_name', $this->key_selfmenu)->find();
    	return is_null($data) ? config('weixin.self_menu') : $data['c_value'];
    }

    /*
     * 获取配置消息
     */
    function getOneCofnigValue($c_name, $c_type) {

        return $this->where(['c_name'=>$c_name, 'c_type'=>$c_type])->value('c_value');
    }

    /*
     * 获取办卡次数配置
     */
    static function card_times() {
        $config = self::get(['c_name'=>'card_times', 'c_type'=>'config']);

        if(empty($config))
            return [];

        return json_decode($config->c_value, true);
    }
}